<template>
  <ControlWrap :custom-style="{background:'rgb(249, 250, 251)'}">
    <!-- 顶部操作区 -->
    <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
      <div class="flex justify-between items-center">
        <el-button type="primary" class="!rounded-button" @click="handleAdd">
          <el-icon class="mr-1"><Plus /></el-icon>新建角色
        </el-button>
        <div class="flex items-center gap-4">
          <el-input
            v-model.trim="searchForm.keyword"
            placeholder="请输入角色名称"
            style="width: 200px"
            :prefix-icon="Search"
            clearable
          />
          <el-select
            v-model="searchForm.status"
            placeholder="角色状态"
            style="width: 100px"
          >
            <el-option label="全部" :value="0" />
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="2" />
          </el-select>
          <el-button
            type="primary"
            class="!rounded-button"
            @click="handleSearch"
          >
            <el-icon class="mr-1"><Search /></el-icon>搜索
          </el-button>
          <el-button class="!rounded-button" @click="resetSearch"
            >重置</el-button
          >
        </div>
      </div>
    </div>
    <!-- 表格区域 -->
    <div class="bg-white rounded-lg shadow-sm p-6">
      <el-table :data="tableData"  border stripe>
        <el-table-column
          prop="role_name"
          fixed="left"
          label="角色名称"
          width="150"
        />

        <el-table-column
          prop="remark"
          min-width="200"
          label="描述"
          show-overflow-tooltip
        />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ dayjs(row.createTime).format("YYYY-MM-DD HH:mm:ss") }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="{ row }">
            {{ dayjs(row.updateTime).format("YYYY-MM-DD HH:mm:ss") }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.status == 1 ? 'success' : 'info'">
              {{ row.status == 1 ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="role_label"
          width="200"
          label="标签"
          show-overflow-tooltip
        />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <div class="flex justify-around">
              <el-button type="primary" link @click="handleEdit(row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button type="primary" link @click="handlePermission(row)">
                <el-icon><Setting /></el-icon>菜单权限
              </el-button>
              <el-button type="danger" link @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @change="handlePageChange"
        />
      </div>
    </div>
    <!-- 角色表单弹窗 -->
    <el-dialog
      :title="dialogType === 'add' ? '新建角色' : '编辑角色'"
      v-if="dialogVisible"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="roleForm" label-width="100px" ref="roleFormRef">
        <el-form-item label="角色名称" prop="name" required>
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="roleForm.status"
            :active-value="1"
            :inactive-value="2"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button class="!rounded-button" @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button
          type="primary"
          class="!rounded-button"
          @click="handleSubmit(roleFormRef)"
          >确定</el-button
        >
      </template>
    </el-dialog>
    <!-- 权限设置弹窗 -->
    <el-dialog
      title="权限设置"
      v-if="permissionDialogVisible"
      v-model="permissionDialogVisible"
      width="600px"
    >
      <el-tree
        ref="permissionTree"
        :data="permissionMenu"
        show-checkbox
        :props="{ label: 'menu_name', children: 'children' }"
        node-key="menu_id"
        :default-checked-keys="checkedPermissions"
      >
        <template #default="{ node, data }">
          <span>{{ node.label }}</span>
        </template>
      </el-tree>
      <template #footer>
        <el-button
          class="!rounded-button"
          @click="permissionDialogVisible = false"
          >取消</el-button
        >
        <el-button
          type="primary"
          class="!rounded-button"
          @click="handlePermissionSubmit"
        >
          保存
        </el-button>
      </template>
    </el-dialog></ControlWrap
  >
</template>
<script lang="ts" setup>
import { computed, onMounted, ref } from "vue";
import { ElMessageBox, ElMessage, FormInstance } from "element-plus";
import { Delete, Edit, Plus, Search, Setting } from "@element-plus/icons-vue";
import { storeToRefs } from "pinia";
import { useUserStore } from "@/store/user";
import {
  addRole,
  getRoleList,
  deleteRole,
  editRole,
  updateRoleMenu,
} from "@/api/role";
import dayjs from "dayjs";
const user = useUserStore();
const { latestMenuList } = storeToRefs(user);
const permissionMenu = computed(() => {
  return latestMenuList.value.slice(1);
});
console.log(permissionMenu.value);
const searchForm = ref({
  keyword: "",
  status: 0,
});
const tableData = ref([]);
const roleFormRef = ref<FormInstance | undefined>(undefined);
const permissionTree: any = ref(null);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(40);
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");
const roleForm = ref({
  id: "",
  name: "",
  description: "",
  status: 1,
});
const permissionDialogVisible = ref(false);
const checkedPermissions = ref<any[]>([]);

const handleSearch = async () => {
  currentPage.value = 1;
  await getRolePageList();
};
const resetSearch = async () => {
  currentPage.value = 1;
  searchForm.value.keyword = "";
  searchForm.value.status = 0;
  await getRolePageList();
};
const handlePageChange = async () => {
  await getRolePageList();
};
const handleAdd = () => {
  dialogType.value = "add";
  roleForm.value.name = "";
  roleForm.value.description = "";
  roleForm.value.status = 1;
  dialogVisible.value = true;
};
const handleEdit = (row: any) => {
  dialogType.value = "edit";
  roleForm.value.name = row.role_name;
  roleForm.value.description = row.remark;
  roleForm.value.status = row.status;
  roleForm.value.id = row.role_id;
  dialogVisible.value = true;
};
const handleDelete = (row: any) => {
  ElMessageBox.confirm("确认删除该角色吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteRole({ roleId: row.role_id, errorMsg: true, successMsg: true }).then(
      (res) => {
        console.log(res);
        getRolePageList();
      }
    );
  });
};
const handlePermission = (row: any) => {
  checkedPermissions.value = row.menuIds.map((item: any) => item.menu_id);
  roleForm.value.id = row.role_id;
  permissionDialogVisible.value = true;
};

const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      console.log("submit!");
      try {
        if (dialogType.value === "add") {
          const res = await addRole({
            roleName: roleForm.value.name,
            roleLabel: "",
            remark: roleForm.value.description,
            status: roleForm.value.status,
            errorMsg: true,
            successMsg: false,
          });
        } else {
          const res = await editRole({
            roleId: roleForm.value.id,
            roleName: roleForm.value.name,
            roleLabel: "",
            remark: roleForm.value.description,
            status: roleForm.value.status,
            errorMsg: true,
            successMsg: false,
          });
        }
        ElMessage.success(dialogType.value === "add" ? "新建成功" : "编辑成功");
        await getRolePageList();
        dialogVisible.value = false;
      } catch (error) {
        console.log(error);
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
const handlePermissionSubmit = async () => {
  const menu_ids = permissionTree.value.getCheckedKeys();
  console.log(menu_ids);
  // return
  const res = await updateRoleMenu({
    roleId: roleForm.value.id,
    menuIds: menu_ids.join(","),
    errorMsg: true,
    successMsg: false,
  });
  console.log(res);
  await getRolePageList();
  permissionDialogVisible.value = false;
  ElMessage.success("权限设置成功");
};
const getRolePageList = async () => {
  try {
    const res = await getRoleList({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      roleName: searchForm.value.keyword,
      status: searchForm.value.status == 0 ? "" : searchForm.value.status,
      errorMsg: true,
      successMsg: true,
    });
    tableData.value = res.list;
    total.value = res.total;
    console.log(res);
  } catch (error) {
    // console.log(error);
    tableData.value = [];
    total.value = 0;
    currentPage.value = 1;
  }
};
onMounted(async () => {
  await getRolePageList();
});
</script>
<style scoped>
:deep(.el-input__wrapper) {
  background-color: #fff;
  border: 1px solid #dcdfe6;
}
:deep(.el-dialog) {
  border-radius: 8px;
}
:deep(.el-select) .el-input__wrapper {
  border: 1px solid #dcdfe6;
}
:deep(.el-button) {
  border-radius: 4px;
}
:deep(.el-pagination) {
  justify-content: flex-end;
}
</style>
